package com.mjsheng.news.service;

import android.app.IntentService;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.mjsheng.news.Utils.Constant;
import com.mjsheng.news.Utils.HttpsUtil;
import com.mjsheng.news.Utils.ImageUtil;
import com.mjsheng.news.Utils.Md5Helper;
import com.mjsheng.news.splash.bean.Ads;
import com.mjsheng.news.splash.bean.AdsDetail;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

/**
 * Created by mjshe on 2017/10/24.
 */
//图片地址转唯一的MD5文件名-->判断图片是否已经存在-->下载图片-->保存到sd卡
public class DownloadingService extends IntentService {

    public static final String ADS_DATE = "ads";
    public DownloadingService() {
        super("DownloadingService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //接收到http请求的对象
        Ads ads = (Ads)intent.getSerializableExtra(ADS_DATE);

        //下载
        List<AdsDetail> list = ads.getAds();
        for(int i=0;i< list.size();i++) {
            AdsDetail adsDetail = list.get(i);
            List<String> imgs = adsDetail.getRes_url();
            if (null != imgs) {
                String img_url = imgs.get(0);
                if (!TextUtils.isEmpty(img_url)) {
                    //图片地址转成唯一的MD5文件名
                    String cache_name = Md5Helper.toMD5(img_url);
                    //先判断图片是否存在,如果存在不下载
                    if (!ImageUtil.checkImageIsDownLoad(cache_name)) {
                        //下载图片
                        //http://ww1.sinaimg.cn/large/b7096bb7gy1fh6x7mlp5fj212j0esafj.jpg
                        downloadImage("http://ww1.sinaimg.cn/large/b7096bb7gy1fgasf3wgqjj20be0gtq39.jpg",cache_name);
                        Log.i("DownloadingService", img_url);
                        Log.i("DownloadingService", "downing");
                    }
                }

            }
        }

    }

    /*
    下载图片
     */
    public void downloadImage(String url,String MD5_name) {
        try {
            //访问链接，拿到连接
//            URL uri = new URL(url);
//            URLConnection urlConnection = uri.openConnection();
            //将网络读取流直接转成位图
            Bitmap bitmap = BitmapFactory.decodeStream(getImageStream(url));
            //往sd卡上写入图片
            saveToSD(bitmap,MD5_name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存到SD卡
     */
    public void saveToSD(Bitmap bitmap,String MD5_name) {
        if (null == bitmap) {
            Log.e("DownloadingService", "bitmap is empty");
            return;
        }
        //判断手机Sd卡是否装载
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //创建图片文件夹
            File SD = Environment.getExternalStorageDirectory();
            File cacheFile = new File(SD, Constant.CACHE);
            if (!cacheFile.exists()) {
                cacheFile.mkdirs();
            }

            File image = new File(cacheFile, MD5_name + "jpg");
            Log.e("DownloadingService", image.getAbsolutePath()+"");
            if (image.exists()) {
                Log.i("DownloadingService", "image is exists");
                return;
            }

            try {
                FileOutputStream image_out = new FileOutputStream(image);
                //bitmap压缩到sd卡
                bitmap.compress(Bitmap.CompressFormat.JPEG, 60, image_out);
                image_out.flush();
                image_out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

    }
    private InputStream getImageStream(String path) throws Exception{


        /*第二种*/
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setRequestMethod("GET");

        // 得到sslContext对象，有两种情况：1.需要安全证书，2.不需要安全证书
        Log.e("geek", "url==" + url);
        Log.e("geek", "是否为https请求==" + (connection instanceof HttpsURLConnection));
        if (connection instanceof HttpsURLConnection) {// 判断是否为https请求
            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();
//            			 SSLContext sslContext = HttpsUtil.getSSLContextWithoutCer();
            if (sslContext != null) {
                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                ((HttpsURLConnection) connection).setDefaultSSLSocketFactory(sslSocketFactory);
//                				((HttpsURLConnection) connection).setHostnameVerifier(HttpsUtil.hostnameVerifier);
            }
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            Log.e("geek", "responseCode==" + responseCode);
            InputStream is = connection.getInputStream();

            Log.e("geek", "is==" + is);
            is.close();
            return is;
        }
        connection.disconnect();
        return null;


/*第一种*/
//        SslUtil.ignoreSsl();
//        URL url = new URL(path);
//
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//        connection.setConnectTimeout(5 * 1000);
//        connection.setRequestMethod("GET");
//        if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
//            return connection.getInputStream();
//        }
//        return null;
    }

}
